package HostTable

import (
	"../util"
	"bufio"
	"fmt"
	"io"
	"os"
	"regexp"
	"strings"
)

var splitExp = regexp.MustCompile("[^\\w:.]")

//从hosts文件的一行字符串中解析出IP和Host
func parseIPHost(line string) (string, string) {
	splited := splitExp.Split(strings.Split(line, "#")[0], -1)
	IP := ""
	Host := ""
	for _, s := range splited {
		if len(s) > 0 {
			if len(IP) <= 0 {
				IP = s
			} else if len(Host) <= 0 {
				Host = s
				return IP, Host
			}
		}
	}
	return IP, Host
}

//读取文件转化为HostTable
func FromFile(path string) error {
	f, err := os.Open(path)
	if err != nil {
		return err
	}
	defer func() { util.LogE(f.Close()) }()
	br := bufio.NewReader(f)
	tableMutex.Lock()
	defer tableMutex.Unlock()
	for {
		l, _, c := br.ReadLine()
		if c == io.EOF {
			break
		}
		IP, Host := parseIPHost(string(l))
		if len(IP) > 0 && len(Host) > 0 {
			table[Host] = IP
		}
	}
	return nil
}

//把HostTable转化为文件
func ToFile(path string) error {
	f, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, os.ModePerm)
	if err != nil {
		return err
	}
	defer func() { util.LogE(f.Close()) }()
	str := ""
	for host, ip := range table {
		str += fmt.Sprintf("%s %s\n", ip, host)
	}
	n, err := f.WriteString(str)
	if err != nil {
		return err
	}
	util.Log(fmt.Sprintf("A %d byte host table written to %s", n, path))
	return nil
}
